/*
 * @Last Modified by: LIWEI
 * @Last Modified time: 2019-08-13 19:48:29
 */

<template>
    <div>
        <!-- 添加设备 -->
        <Modal
            v-model="isVisible"
            :mask-closable="false"
            class-name="vertical-center-modal"
            title="添加设备"
            @on-visible-change="onVisibleChange">

            <Form ref="addForm" :model="formData" :rules="formRules" :label-width="120" autocomplete="off" :show-message="false">
                <FormItem label=" 设备 SN " prop="sn" class="form-item">
                    <Input v-model.trim="formData.sn" @on-change="sn2model" type="text" autocomplete="off" placeholder="请输入设备 SN" :maxlength="100"/>
                </FormItem>

                <FormItem label="设备类型" class="form-item" prop="type_id">
                    <Select v-model="formData.type_id" @on-change="selectDeviceType" placeholder="请选择设备类型">
                        <Option v-for="item in filterDeviceTypes" :value="item.id" :key="item.id">{{ item.name }}</Option>
                    </Select>
                </FormItem>

                <!-- 绑定 网关、普通电表、水表、水表网关、无网关门锁时要隐藏 -->
                <FormItem label="关联网关" class="form-item" v-show="isGatewayVisible">
                    <Select v-model="formData.gateway_id">
                        <!-- <Option value="0">请选择关联网关</Option> -->
                        <Option 
                        v-for="item in devices" 
                        v-if="item.device_type === DeviceTypeEnum.GATEWAY || (item.device_ability && item.device_ability.indexOf('GW') > -1)" 
                        :value="item.id" :key="item.id"
                        >{{ item.description }}</Option>
                    </Select>
                </FormItem>

                <FormItem label="随机码" prop="code" class="form-item" v-show="isCodeVisible">
                    <Input v-model="formData.code" type="text" placeholder="随机码" :maxlength="20"/>
                </FormItem>

                <FormItem label="关联水表网关" v-show="isWaterGatewayVisible" class="form-item">
                    <Select v-model="formData.water_gateway_id">
                        <!-- <Option value="0">请选择关联水表网关</Option> -->
                        <Option v-for="item in devices" v-if="item.device_type === DeviceTypeEnum.WATERGATEWAY" :value="item.id" :key="item.id">{{ item.description }}</Option>
                    </Select>
                </FormItem>

                <FormItem label="关联采集器" v-show="isElecollectorVisible" class="form-item">
                    <Select v-model="formData.elecollector_id">
                        <!-- <Option value="0">请选择关联采集器</Option> -->
                        <Option v-for="item in devices" v-if="item.device_type === DeviceTypeEnum.ELECOLLECTOR || (item.device_ability && item.device_ability.indexOf('ELEC') > -1)" :value="item.id" :key="item.id">{{ item.description }}</Option>
                    </Select>
                </FormItem>
                
                <FormItem label="门禁类型" class="form-item" prop="guardName" v-if="isaccessControll">
                    <Select v-model="formData.guardName" ref="formRoom" placeholder="请选择门禁类型" @on-change="accessControllType">
                        <Option v-for="item in entranceGuardTypes" :value="item.id" :key="item.id">{{ item.guardName }}</Option>
                    </Select>
                </FormItem>

                <!--<FormItem label="绑定位置" class="form-item" prop="room_id" v-show="!isBuilding">
                    <Select v-if="isVisible" ref="formRoom" filterable v-model="formData.room_id" :loading="loading1" remote @on-change="selectRoom">
                        <Option v-for="item in roomsFiltrate" :value="item.id" :key="item.id">{{ util.getRoomName(item) }}</Option>
                    </Select>
                </FormItem>-->

                <FormItem label="绑定位置" class="form-item" prop="room_id" v-show="!isBuilding">
                    <Select
                        v-if="isVisible"
                        ref="formRoomLocation"
                        @on-change="selectRoom"
                        filterable
                        clearable
                        remote
                        :remote-method="inputSelect"
                        :loading="loading1">
                        <Option v-for="item in roomsFiltrate" :value="item.id" :key="item.id">{{ util.getRoomName(item) }}</Option>
                    </Select>
                </FormItem>

                <FormItem label="所属楼栋" class="form-item" v-show="isBuilding" prop="room_id">
                    <Select remote=false @on-change="selectBuilding" placeholder="请选择所属楼栋">
                        <Option v-for="item in roomsFiltrate" :value="item.id" :key="item.id">{{ util.getRoomName(item) }}</Option>
                    </Select>
                </FormItem>

                
                <FormItem label="设备名称" prop="name" class="form-item">
                    <Input v-model="formData.name" type="text" placeholder="设备名称" :maxlength="100"/>
                </FormItem>

                <FormItem class="form-item" v-show="formData.type_id === DeviceTypeEnum.REPEATER">
                    <div style="line-height:1.5">请确认已完成中继器配对（绿灯），再执行下一步操作！</div>
                </FormItem>

                <FormItem class="form-item" v-show="formData.type_id === DeviceTypeIds.ELEMETER_AMC1">
                    <div style="line-height:1.5;color:#f00;">AMC1只能通过无线与AMW1 或 AMG1连接，不能使用485线。</div>
                </FormItem>
            </Form>

            <div slot="footer">
                <Button type="ghost" size="large" @click="hideModal('addForm')">取消</Button>
                <Button type="primary" size="large" @click="submit('addForm')">确定</Button>
            </div>
        </Modal>

        <!-- 添加设备成功 -->
        <Modal
            v-model="isProcessModalVisible"
            title="添加设备状态"
            :mask-closable="false"
            :closable="false">

            <div v-if="bindTip" class="bind-tip">
                <div class="bind-tip-title">＊ 操作完成之前请不要关闭此页面</div>
                <div v-html="bindTip"></div>
            </div>

            <div class="loading" v-if="bindStatus == 1">
                <Spin fix>
                    <Icon type="load-c" size=18 class="spin-icon-load"></Icon>
                    <div>查询绑定状态... {{progress}}%</div>
                </Spin>
            </div>

            <div v-show="bindStatus == 1 || bindStatus == 2" style="margin: 20px 20px 0px;">
                <Progress hide-info :percent="progress" :stroke-width="16"></Progress>
            </div>

            <div v-if="bindStatus == 2" class="bind-tip bind-success">
                绑定成功
            </div>

            <div v-if="bindStatus == 3" class="bind-tip bind-failed">
                绑定超时
            </div>

            <div slot="footer">
                <!-- <Button type="primary" size="large" @click="closeProcessModal()" v-if="bindStatus !== 1">确定</Button> -->
            </div>
        </Modal>

    </div>
</template>

<script>
// import { DeviceTypeEnum, RoomTypeEnum } from '@/libs/const';
import { DeviceTypeEnum } from '@/libs/const'
import util from '@/libs/util'
import { http, api } from '@/libs/http'
import { refreshRoom } from './room-list/util'
import debounce from 'lodash/debounce'

const DeviceTypeIds = {
  GATEWAY: 1,
  GATEWAY_G5: 11,
  LOCK: 2,
  LOCK_NO_GATEWAY: 21,
  ELEMETER: 3,
  ELEMETER_AMC1: 30,
  ELEMETER_A1Z: 31,
  ELEMETER_A4: 32,
  ELEMETER_AMG1: 33,
  ELECOLLECTOR: 4,
  WATER_GATEWAY: 5,
  WATERMETER: 6,
  REPEATER: 8,
  FACE_ACCESS: 10,
  M3_ACCESS: 11
}
const deviceTypes = [
  { id: DeviceTypeIds.GATEWAY, name: '门锁网关或电表网关' },
  { id: DeviceTypeIds.LOCK, name: '有网关门锁' },
  { id: DeviceTypeIds.LOCK_NO_GATEWAY, name: '无网关门锁' },
  { id: DeviceTypeIds.ELECOLLECTOR, name: '电表采集器' },
  { id: DeviceTypeIds.ELEMETER, name: '电表A1、A2、A3、AT120、A1P' },
  { id: DeviceTypeIds.ELEMETER_AMC1, name: '电表AMC1(兼有采集器功能)' },
  { id: DeviceTypeIds.ELEMETER_A1Z, name: '电表A1Z、A1PZ' },
  { id: DeviceTypeIds.ELEMETER_A4, name: '电表A4、A4P' },
  { id: DeviceTypeIds.ELEMETER_AMG1, name: '电表AMG1(兼有网关、采集器功能)' },
  { id: DeviceTypeIds.WATER_GATEWAY, name: '水表网关' },
  { id: DeviceTypeIds.WATERMETER, name: '水表' },
  { id: DeviceTypeIds.FACE_ACCESS, name: '门禁' },
  { id: DeviceTypeIds.M3_ACCESS, name: 'M3门禁' }
  // { id: DeviceTypeIds.REPEATER, name: '中继器(mesh组网)' }
]

const DeviceTips = {
  [DeviceTypeIds.GATEWAY_G5]: '长按设备左侧配置孔4~6秒激活sim卡',
  [DeviceTypeIds.LOCK]: {
    D2F: '当前绑定D2F门锁：<br>连续戳三下小孔等待屏幕闪烁后进入配置模式',
    v5750: '连续戳三下小孔等待屏幕闪烁后进入配置模式',
    D1T1: '长按小孔等待屏幕闪烁后进入配置模式',
    lessV5750: '长按小孔等待屏幕闪烁后进入配置模式',
    T3_HUAWEI: '当前T3/D3门锁绑定到华为网关：<br>1.请轻触门锁面板虚拟按键点亮面板，长按 “＊”，门锁发出“滴滴”声；<br>2.输入“1”，待门锁发出“滴滴”声；<br>3.输入SN后四位，等待屏幕闪烁进入配置模式。',
    T3: '当前绑定T3/D3门锁：<br>1.请轻触门锁面板虚拟按键点亮面板，长按 “＊”，门锁发出“滴滴”声；<br>2.输入SN后四位，等待屏幕闪烁进入配置模式。',
    D3: '当前绑定D3门锁: <br>1.请轻触门锁面板虚拟按键点亮面板，长按 “＊”，门锁发出“滴滴”声；<br>2.输入SN后四位，等待屏幕闪烁进入配置模式。 ',
    D3_HUAWEI: '当前绑定D3门锁: <br>1.请轻触门锁面板虚拟按键点亮面板, 按 “#”, 再长按"*", 门锁发出“滴滴”声;输入“1”, 待门锁发出“滴滴”, <br>3.输入SN后四位，等待屏幕闪烁进入配置模式。'
  },
  [DeviceTypeIds.ELEMETER]: '绑定中，请稍候...',
  [DeviceTypeIds.ELEMETER_AMC1]: '长按配置键直到显示C0008，然后松手，电表会进入配对状态',
  [DeviceTypeIds.ELEMETER_A1Z]: '按住设备配置键5秒后松手，液晶显示屏出现C0100',
  [DeviceTypeIds.ELEMETER_A4]: '戳设备左侧配置孔5秒后松手，液晶显示屏出现C0100',
  [DeviceTypeIds.ELEMETER_AMG1]: '绑定中，请稍候...',
  [DeviceTypeIds.ELECOLLECTOR]: '长戳设备指示灯下方按钮直至蓝灯闪烁',
  [DeviceTypeIds.WATERMETER]: '绑定中，请稍候...',
  [DeviceTypeIds.REPEATER]: '请确认已完成中继器配对（绿灯）'
}
const BindStatus = {
  BINDING: 1,
  SUCCESS: 2,
  FAIL: 3,
  TIMEOUT: 4
}
const EntranceId = {
  COMMUNITY: 2, // 小区大门
  UNIT: 3 // 单元门
}

const RoomType = {
  1: 'commonRoom', // 公区和房间
  2: 'publicRoom', // 公区
  3: 'buildingRoom', // 获取楼栋
  4: 'room'// 房间
}
const CheckBindMaxTime = 150000 // 检查绑定状态最大时间（MS）
const CheckBindPer = 5000 // 检查绑定状态间隔（MS）

let _checkBindTimer = -1
let _checkBindTimes = 1
let _checkBindMaxTimes = CheckBindMaxTime / CheckBindPer

export default {
  name: 'addDevice',
  props: {
    homeId: Number,
    rooms: Array,
    homeInfo: Object,
    devices: Array,
    visible: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      DeviceTypeIds,
      util: util,
      DeviceTypeEnum: DeviceTypeEnum,
      isProcessModalVisible: false,

      isGatewayVisible: false,
      isWaterGatewayVisible: false,
      isElecollectorVisible: false,
      isCodeVisible: false,
      isaccessControll: false,

      formData: {
        room_id: '',
        type_id: 0,
        name: '',
        sn: '',
        gateway_id: 0,
        water_gateway_id: 0,
        elecollector_id: 0,
        code: '',
        guardName: ''// 门禁类型
      },
      formRules: {
        guardName: [{ required: true, type: 'integer', message: '', trigger: 'blur' }],
        room_id: [{ required: true, type: 'integer', message: '', trigger: 'blur' }],
        type_id: [{ required: true, type: 'integer', message: '', trigger: 'blur' }],
        name: [{ required: true, message: '不能为空', trigger: 'blur' }],
        sn: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      entranceGuardTypes: [],
      deviceTypes,
      gateways: [],

      selectedRoomId: 0,
      bindTip: '',
      bindStatus: 0,
      progress: 0,
      gatewaySn: '',
      isBuilding: false,
      roomsFiltrate: [], // 过滤后的房间数据(公区 、 房间、 楼栋)
      isFace: this.$store.state.user.hasFaceAccessPermission,

      loading1: false,
      accessControllTypeVal: ''// 保存上一次获取房间的type，清空绑定位置用
    }
  },

  computed: {
    isVisible: {
      get: function () {
        return this.visible
      },

      set: function (val) {
        this.$emit('on-close', val)
      }
    },
    gatewayIsAmgOrAmw () {
      const elemeterType = this.gatewaySn.substring(6, 8)

      if (elemeterType === '07' || elemeterType === '08') {
        return true
      } else {
        return false
      }
    },
    // filterDeviceTypes () {
    //     // this.isFace ? this.deviceTypes :
    //     return this.deviceTypes.filter(item => {
    //         item.id != 10;
    //     });
    // }
    filterDeviceTypes: function () {
      return this.isFace ? this.deviceTypes : this.deviceTypes.filter(function (item) {
        return item.id !== DeviceTypeIds.FACE_ACCESS
      })
    }
  },

  // mounted() {
  //     this.reset()
  // },

  created () {
    // 门禁类型控制判断显示所属楼栋
    if (this.homeInfo && this.homeInfo.home_type === 1) { // 1分散式
      this.entranceGuardTypes = [{id: EntranceId.COMMUNITY, guardName: '小区大门'}]
    } else {
      this.entranceGuardTypes = [
        {id: EntranceId.COMMUNITY, guardName: '小区大门'},
        {id: EntranceId.UNIT, guardName: '单元门'}
      ]
    }
  },

  methods: {
    selectGateway (item) {
      if (!item) {
        return
      }
      const { label } = item
      this.gatewaySn = label
    },

    // 设备sn
    sn2model (event) {
      const sn = this.formData.sn
      const model = util.sn2model(sn)
      if (model) {
        this.formData.type_id = model.id
        this.selectDeviceType(model.id, sn)
      } else {
        this.formData.type_id = 0
      }
    },

    // 取消
    hideModal (name) {
      this.resetForm(name)
      this.isVisible = false
      this.reset()
    },

    // 添加设备
    onVisibleChange (visible) {
      this.formData.room_id = 0
      this.resetForm('addForm')
      this.reset()
      // if (!visible) {
      //     this.resetForm('addForm');
      // } else {
      // }
    },

    // 设备类型
    selectDeviceType (id) {
      this.formData.guardName = ''// 门禁类型
      this.formData.room_id = ''// 绑定位置
      this.formData.name = ''// 设备名称
      this.isBuilding = false// 重置为绑定位置
      if (this.$refs['formRoomLocation']) {
        this.$refs['formRoomLocation'].clearSingleSelect()// 清空绑定位置
      }

      for (let item of deviceTypes) {
        // this.deviceTypes.push(item);
        if (item.id === id) {
          this.formData.type_id = id
          // this.deviceTypes.push(item);
          break
        }
      }
      if (this.formData.type_id === DeviceTypeIds.ELEMETER_A4) {
        this.rooms.forEach(item => {
          if (item.room_type !== 2) {
            this.roomsFiltrate.push(item)
          }
        })
        this.accessControllType(4)// 只能安装到房间
      } else if (this.formData.type_id === DeviceTypeIds.GATEWAY ||
                        this.formData.type_id === DeviceTypeIds.WATER_GATEWAY ||
                        this.formData.type_id === DeviceTypeIds.ELECOLLECTOR ||
                        this.formData.type_id === DeviceTypeIds.M3_ACCESS) {
        this.rooms.forEach(item => {
          if (item.room_type === 2) {
            this.roomsFiltrate.push(item)
          }
        })
        this.accessControllType(2)// 只能安装到公区
      } else if (this.formData.type_id === DeviceTypeIds.FACE_ACCESS) {
        // 单元门
        this.accessControllType(3)// 楼栋
      } else {
        this.rooms.forEach(item => {
          this.roomsFiltrate.push(item)
        })
        this.accessControllType(1)// 所有
      }

      this.isGatewayVisible =
                id === DeviceTypeIds.LOCK ||
                id === DeviceTypeIds.ELECOLLECTOR ||
                id === DeviceTypeIds.ELEMETER_AMC1 ||
                id === DeviceTypeIds.ELEMETER_A1Z ||
                id === DeviceTypeIds.ELEMETER_A4 ||
                id === DeviceTypeIds.REPEATER

      this.isWaterGatewayVisible = id === DeviceTypeIds.WATERMETER
      this.isElecollectorVisible = id === DeviceTypeIds.ELEMETER
      this.isCodeVisible = id === DeviceTypeIds.LOCK_NO_GATEWAY
      this.isaccessControll = id === DeviceTypeIds.FACE_ACCESS
    },

    // 选择楼栋
    selectBuilding (id) {
      this.formData.room_id = id
    },

    // 绑定位置
    selectRoom (id) {
      if (id) {
        this.formData.room_id = id
      } else {
        this.formData.room_id = ''
        this.accessControllType(this.accessControllTypeVal, null)// 房间
      }
    },

    getElecollectorInfo (id) {
      for (let item of this.devices) {
        if (item.id === id) {
          return item
        }
      }
      return null
    },

    // 输入检索 绑定位置
    inputSelect (query) {
      this.accessControllType(this.accessControllTypeVal, query)// 房间
    },

    // 门禁类型
    accessControllType (type, query) {
      // this.$refs['formRoomLocation'].clearSingleSelect();//清空绑定位置
      this.isBuilding = type === 3
      this.accessControllTypeVal = type
      let params = {
        'with_building': 1,
        'room_type': RoomType[type] || null,
        'keyword': query || null
      }
      http.request(this, api.room_list, [this.homeId], params, (res, err) => { // 1098194355
        if (err || !res) {
          return
        }
        if (res.length) {
          this.roomsFiltrate = []
          res.forEach((item, index) => {
            item.room_name = item.building && item.building.room_name ? item.room_name + '-' + item.building.room_name : item.room_name
          })
          this.roomsFiltrate = res
          // if (this.roomsFiltrate.length == 1) {
          //     this.formData.room_id = this.roomsFiltrate[0].id;
          // } else {
          //     this.formData.room_id = '';
          // }
        }
      })
    },

    // 确定
    submit: debounce(function (name) {
      this.$refs[name].validate(async valid => {
        if (!valid) {
          return
        }

        // let home = this.home,
        let formData = this.formData
        let params = {
          description: formData.name,
          sn: formData.sn
        }

        util.log('addDevice:', formData, params)
        this.selectedRoomId = formData.room_id
        switch (formData.type_id) {
          case DeviceTypeIds.GATEWAY:
            params.device_type = DeviceTypeEnum.GATEWAY
            http.request(this, api.gateway_add, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.SUCCESS)
              // this.$emit('on-load-device') //更新网关之后更新device
              this.hideModal(name)
            })
            break

          case DeviceTypeIds.LOCK:
            params.gateway_id = formData.gateway_id

            if (!params.gateway_id) {
              this.$Message.error('请选择网关')
              return
            }
            let lockType
            const isD1 = util.sn2model(params.sn) && util.sn2model(params.sn).device === 'D1'
            const isT1 = util.sn2model(params.sn) && util.sn2model(params.sn).device === 'T1'
            const isD2F = util.sn2model(params.sn) && util.sn2model(params.sn).device === 'D2F'
            const isT3 = util.sn2model(params.sn) && util.sn2model(params.sn).device === 'T3'
            const isD3 = util.sn2model(params.sn) && util.sn2model(params.sn).device === 'D3'
            let isHuaweiGateway // 是否华为网关
            this.devices.forEach(item => {
              if (item.id === formData.gateway_id) {
                const gatewaySn = item.sn
                isHuaweiGateway = util.sn2model(gatewaySn) && util.sn2model(gatewaySn).device === 'GATEWAY_HUAWEI'
              }
            })
            util.log('是否华为网关', isHuaweiGateway)
            util.log('绑定门锁型号', lockType)

            if (isD2F) {
              lockType = 'D2F'
            } else if (isT3 && isHuaweiGateway) {
              lockType = 'T3_HUAWEI'
            } else if (isT3) {
              lockType = 'T3'
            } else if (isD3) {
              lockType = isHuaweiGateway ? 'D3_HUAWEI' : 'D3'
            } else if (isD1 || isT1) {
              lockType = 'D1T1'
            } else {
              util.log('不是D1T1')
              // 判断门锁版本号
              lockType = 'v5750'
              const res = await http.req(api.lock_version_get, [params.sn], null)
              const versionFlag = [5, 7, 5, 0]
              let currentFlag = res.app_version.split('.')
              for (let i = 0; i < 4; i++) {
                // 比较版本号
                if (Number(currentFlag[i]) < versionFlag[i]) {
                  lockType = 'lessV5750'
                  break
                } else if (Number(currentFlag[i]) > versionFlag[i]) {
                  lockType = 'v5750'
                  break
                }
              }
            }
            this.bindTip = DeviceTips[formData.type_id] && DeviceTips[formData.type_id][lockType]

            // 发送绑定请求
            http.request(this, api.lock_add, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                this.isProcessModalVisible = false
                return
              }
              this.isProcessModalVisible = true
              let { process_id } = res
              this.getLockBindStatus(process_id) // 轮训查看是否绑定成功
            })
            break

          case DeviceTypeIds.LOCK_NO_GATEWAY:
            params.code = formData.code

            if (!params.code) {
              this.$Message.error('请输入随机码')
              return
            }

            http.request(this, api.lock_add_no_gate, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.bindTip = ''
              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.SUCCESS)
              this.hideModal(name)
            })
            break

          case DeviceTypeIds.ELEMETER:
            params.parent_id = formData.elecollector_id

            if (!params.parent_id) {
              this.$Message.error('请选择电表采集器')
              return
            }

            let elecollector = this.getElecollectorInfo(formData.elecollector_id)
            if (!elecollector) {
              this.$Message.error('找不到指定电表采集器')
              return
            }

            // params.model = elecollector.model;

            let elemeterType = formData.sn.substr(6, 2)
            params.model = elemeterType === '80' ? 'AT120' : 'DDSU1225'

            http.request(this, api.elemeter_create, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }
              // this.isProcessModalVisible = true
              // this.setBindStatus(BindStatus.SUCCESS)
              // this.hideModal(name)

              this.setBindStatus(BindStatus.BINDING)
              this.isProcessModalVisible = true
              this.bindTip = DeviceTips[formData.type_id]
              this.getElemeterBindStatus(params.sn, res.process_id)
            })
            break
          case DeviceTypeIds.ELEMETER_AMC1:
          case DeviceTypeIds.ELEMETER_A1Z:
          case DeviceTypeIds.ELEMETER_A4:
            params.parent_id = formData.gateway_id

            if (!params.parent_id) {
              this.$Message.error('请选择网关')
              return
            }

            if (formData.type_id === DeviceTypeIds.ELEMETER_A1Z) {
              params.model = 'DSZM-B01'
            } else if (formData.type_id === DeviceTypeIds.ELEMETER_A4) {
              params.model = 'DSZM-B02'
            }

            http.request(this, api.elemeter_create, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.setBindStatus(BindStatus.BINDING)
              this.isProcessModalVisible = true
              this.bindTip = DeviceTips[formData.type_id]
              this.getElemeterBindStatus(params.sn, res.process_id)
            })
            break
          case DeviceTypeIds.ELEMETER_AMG1:
            http.request(this, api.elemeter_create, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.setBindStatus(BindStatus.BINDING)
              this.isProcessModalVisible = true
              this.bindTip = DeviceTips[formData.type_id]
              this.getElemeterBindStatus(params.sn, res.process_id)
            })
            break

          case DeviceTypeIds.ELECOLLECTOR:
            params.gateway_id = formData.gateway_id

            if (!params.gateway_id) {
              this.$Message.error('请选择网关')
              return
            }

            http.request(this, api.elecollector_create, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.BINDING)
              this.bindTip = DeviceTips[formData.type_id]
              this.getElecollectorBindStatus(params.sn, res.process_id)
            })
            break

          case DeviceTypeIds.WATER_GATEWAY:
            http.request(this, api.watergateway_create, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.SUCCESS)
              this.hideModal(name)
            })
            break

          case DeviceTypeIds.WATERMETER:
            params.water_gateway_id = formData.water_gateway_id

            if (!params.water_gateway_id) {
              this.$Message.error('请选择水表网关')
              return
            }

            http.request(this, api.watermeter_create, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.BINDING)
              this.bindTip = DeviceTips[formData.type_id]
              this.getWatermeterBindStatus(res.sn, res.process_id)
            })
            break

          case DeviceTypeIds.REPEATER:
            params.gateway_id = formData.gateway_id

            if (!params.gateway_id) {
              this.$Message.error('请选择网关')
              return
            }
            this.isProcessModalVisible = true
            this.setBindStatus(BindStatus.BINDING)
            this.bindTip = DeviceTips[formData.type_id]
            this.getRepeaterBindStatus(params, formData.room_id)

            break

          case DeviceTypeIds.FACE_ACCESS: // 人脸门禁
            http.request(this, api.face_accesss_add_device, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.SUCCESS)
              this.bindTip = DeviceTips[formData.type_id]
            })
            break
          case DeviceTypeIds.M3_ACCESS: // M3门禁
            http.request(this, api.m3_accesss_add_device, [formData.room_id], params, (res, err) => {
              if (err || !res) {
                return
              }

              this.isProcessModalVisible = true
              this.setBindStatus(BindStatus.SUCCESS)
              this.bindTip = DeviceTips[formData.type_id]
            })
            break
        }
      })
    }, 300),

    // 获取门锁绑定状态
    getLockBindStatus (process_id) {
      this.clearTimer()
      _checkBindTimer = setInterval(() => {
        if (_checkBindTimes > _checkBindMaxTimes) {
          this.clearTimer()
          this.setBindStatus(BindStatus.TIMEOUT)
          return
        }

        _checkBindTimes++

        http.request(this, api.lock_bind_status, [this.formData.room_id], { sn: this.formData.sn, process_id: process_id }, (res, err) => {
          if (err || !res) {
            this.$Notice.error({
              title: '查询绑定状态失败'
            })
            return
          }

          this.setBindStatus(res.status, res.err_no)
        })
      }, CheckBindPer)
    },

    // 获取电表绑定状态
    getElemeterBindStatus (sn, process_id) {
      util.log('getElemeterBindStatus:', sn, process_id)
      this.clearTimer()
      _checkBindTimer = setInterval(() => {
        util.log('_checkBindTimes:', _checkBindTimes)
        if (_checkBindTimes >= _checkBindMaxTimes) {
          this.clearTimer()
          this.setBindStatus(BindStatus.TIMEOUT)
          return
        }

        _checkBindTimes++

        http.request(this, api.elemeter_check, [this.formData.room_id], { sn, process_id: Number(process_id) }, (res, err) => {
          if (err || !res) {
            this.$Notice.error({
              title: '查询绑定状态失败'
            })
            return
          }

          this.setBindStatus(res.status, res.err_no)
        })
      }, CheckBindPer)
    },

    // 获取采集器绑定状态
    getElecollectorBindStatus (sn, process_id) {
      this.clearTimer()
      _checkBindTimer = setInterval(() => {
        if (_checkBindTimes > _checkBindMaxTimes) {
          this.clearTimer()
          this.setBindStatus(BindStatus.TIMEOUT)
          return
        }

        _checkBindTimes++

        http.request(this, api.elecollector_check, [this.formData.room_id], { sn, process_id: Number(process_id) }, (res, err) => {
          if (err || !res) {
            this.$Notice.error({
              title: '查询绑定状态失败'
            })
            return
          }

          this.setBindStatus(res.status, res.err_no)
        })
      }, CheckBindPer)
    },

    // 获取水表绑定状态
    getWatermeterBindStatus (sn, process_id) {
      this.clearTimer()
      _checkBindTimer = setInterval(() => {
        if (_checkBindTimes > _checkBindMaxTimes) {
          this.clearTimer()
          this.setBindStatus(BindStatus.TIMEOUT)
          return
        }

        _checkBindTimes++

        http.request(this, api.watermeter_bind_process, [this.formData.room_id], { sn, process_id: Number(process_id) }, (res, err) => {
          if (err || !res) {
            this.$Notice.error({
              title: '查询绑定状态失败'
            })
            return
          }

          this.setBindStatus(res.status, res.err_no)
        })
      }, CheckBindPer)
    },

    // 获取中继器绑定状态
    getRepeaterBindStatus (params, roomId) {
      this.clearTimer()
      _checkBindTimer = setInterval(() => {
        if (_checkBindTimes > _checkBindMaxTimes) {
          this.clearTimer()
          this.setBindStatus(BindStatus.TIMEOUT)
          return
        }

        _checkBindTimes++
        util.log(params, roomId)
        this.setBindStatus(BindStatus.BINDING)
        // http.request(this, api.watermeter_bind_process, [this.formData.room_id], { sn, process_id: Number(process_id) }, (res, err) => {
        //     if (err || !res) {
        //         this.$Notice.error({
        //             title: '查询绑定状态失败',
        //         });
        //         return
        //     }

        //     this.setBindStatus(res.status, res.err_no)
        // })
      }, CheckBindPer)
    },

    // 设置绑定结果
    // 1:绑定中,2:成功,3:超时
    setBindStatus (status, err_no) {
      let progress = parseInt(_checkBindTimes * 100 / _checkBindMaxTimes)
      if (progress >= 100) {
        // 已超时
        progress = 99
      }
      this.progress = progress
      util.log('setBindStatus:', status, this.progress)
      this.bindStatus = status

      if (status === BindStatus.TIMEOUT) {
        this.$Notice.error({
          title: '绑定超时，请重试'
        })
      }

      if (status === BindStatus.FAIL) {
        this.$Notice.error({
          title: `绑定失败，错误码 ${err_no || '未知'}`
        })
      }

      if (status === BindStatus.SUCCESS) {
        this.progress = 100
        this.$Notice.success({
          title: '设备绑定成功。'
        })

        const roomId = this.formData.room_id
        const homeId = this.homeId

        refreshRoom(homeId, roomId)

        if (this.isVisible) {
          this.hideModal('addForm')
        }
      }

      if (status === BindStatus.SUCCESS || status === BindStatus.TIMEOUT || status === BindStatus.FAIL) {
        this.clearTimer()
        this.closeProcessModal()
        this.$emit('on-load-device') // 更新device
      }
    },

    clearTimer () {
      clearInterval(_checkBindTimer)
      _checkBindTimer = -1
      _checkBindTimes = 1
    },

    resetForm (name) {
      this.$refs[name].resetFields()
    },

    reset () {
      this.clearTimer()
      // this.clearProcessTimer();
      this.progress = 0
      _checkBindTimes = 0
      this.bindFailed = false
      this.bindSuccess = false

      // this.$refs['formRoom'].setQuery('')

      this.$set(this.formData, 'room_id', 0)
      this.formData.type_id = '0'
      this.formData.name = ''
      this.formData.sn = ''
      this.formData.gateway_id = '0'
      this.formData.water_gateway_id = '0'
      this.formData.elecollector_id = '0'
      this.formData.code = ''
    },

    closeProcessModal () {
      this.bindStatus = ''
      this.isProcessModalVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
.form-item {
    width: 90%;
    margin-bottom: 18px;
}
.bind-tip {
    .bind-tip-title{
        text-align: center;
        color: #05bacb;
        font-weight: bold;
        margin-bottom: 10px;
    }
    width: 100%;
    padding: 10px 20px 0;
    font-size: 18px;
    line-height: 1.5;
}
.bind-failed {
    color: #ff4d4d;
}
.bind-success {
    color: #59d583;
}

.loading {
    position: relative;
    padding: 20px 0;
}

.spin-icon-load {
    animation: ani-spin 1s linear infinite;
}
@keyframes ani-spin {
    from {
        transform: rotate(0deg);
    }
    50% {
        transform: rotate(180deg);
    }
    to {
        transform: rotate(360deg);
    }
}
</style>